const Product = require('../models/Product');
const { getStoreById } = require('../models/Store');

/**
 * 获取店铺产品列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getProducts = async (req, res) => {
    try {
        const { storeId } = req.params;
        const { sort = 'price', asc = 1, keyword = '', page = 1, pageSize = 10 } = req.query;
        
        // 验证店铺是否存在且类型为农产品
        const store = await getStoreById(storeId);
        if (!store) {
            return res.status(404).json({
                success: false,
                message: '店铺不存在'
            });
        }
        
        if (store.type !== '农产品') {
            return res.status(400).json({
                success: false,
                message: '该店铺不是农产品类型'
            });
        }
        
        const options = {
            storeId,
            sort,
            asc: parseInt(asc),
            keyword,
            page: parseInt(page),
            pageSize: parseInt(pageSize)
        };
        
        const result = await Product.getProductsByStoreId(options);
        
        res.json({
            success: true,
            data: result.list,
            pagination: result.pagination
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取产品列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品列表失败'
        });
    }
};

/**
 * 获取产品详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getProductDetail = async (req, res) => {
    try {
        const { productId } = req.params;
        
        const product = await Product.getProductById(productId);
        if (!product) {
            return res.status(404).json({
                success: false,
                message: '产品不存在'
            });
        }
        
        res.json({
            success: true,
            data: product
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取产品详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品详情失败'
        });
    }
};

/**
 * 创建产品订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const createProductOrder = async (req, res) => {
    try {
        const userId = req.user.userId;
        const { productId } = req.params;
        const { 
            quantity, 
            isDepositOnly,
            shippingAddress,
            contactName,
            contactPhone,
            remarks
        } = req.body;
        
        if (!quantity || quantity <= 0) {
            return res.status(400).json({
                success: false,
                message: '购买数量必须大于0'
            });
        }
        
        if (!shippingAddress || !contactName || !contactPhone) {
            return res.status(400).json({
                success: false,
                message: '请填写完整的收货信息'
            });
        }
        
        // 获取产品信息
        const product = await Product.getProductById(productId);
        if (!product) {
            return res.status(404).json({
                success: false,
                message: '产品不存在'
            });
        }
        
        // 检查库存
        if (product.stock < quantity) {
            return res.status(400).json({
                success: false,
                message: '库存不足'
            });
        }
        
        // 计算价格
        const price = product.price;
        const totalPrice = price * quantity;
        
        // 计算定金（通常为总价的30%）
        const depositAmount = isDepositOnly ? Math.round(totalPrice * 0.3) : 0;
        
        // 创建订单
        const orderData = {
            user_id: userId,
            store_id: product.store_id,
            product_id: product.id,
            quantity,
            price,
            total_price: totalPrice,
            deposit_amount: depositAmount,
            payment_method: 'wechat', // 默认微信支付
            status: 'pending', // 待支付
            shipping_address: shippingAddress,
            contact_name: contactName,
            contact_phone: contactPhone,
            remarks
        };
        
        const orderId = await Product.createProductOrder(orderData);
        
        res.status(201).json({
            success: true,
            data: {
                orderId,
                totalPrice,
                depositAmount,
                paymentAmount: isDepositOnly ? depositAmount : totalPrice
            },
            message: '订单创建成功，请继续完成支付'
        });
    } catch (error) {
        console.error('[CONTROLLER] 创建产品订单失败:', error);
        res.status(500).json({
            success: false,
            message: '创建产品订单失败'
        });
    }
};

/**
 * 获取用户的产品订单列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getUserProductOrders = async (req, res) => {
    try {
        const userId = req.user.userId;
        
        const orders = await Product.getUserProductOrders(userId);
        
        res.json({
            success: true,
            data: orders
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取用户产品订单列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户产品订单列表失败'
        });
    }
};

/**
 * 获取店铺的产品订单列表（商家接口）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getStoreProductOrders = async (req, res) => {
    try {
        const { storeId } = req.params;
        
        // 验证当前用户是否为该店铺的所有者
        const userId = req.user.userId;
        const store = await getStoreById(storeId);
        
        if (!store || store.owner_id !== userId) {
            return res.status(403).json({
                success: false,
                message: '无权访问该店铺的订单信息'
            });
        }
        
        const orders = await Product.getStoreProductOrders(storeId);
        
        res.json({
            success: true,
            data: orders
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取店铺产品订单列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取店铺产品订单列表失败'
        });
    }
};

/**
 * 更新产品订单状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const updateProductOrderStatus = async (req, res) => {
    try {
        const { orderId } = req.params;
        const { status } = req.body;
        
        if (!status) {
            return res.status(400).json({
                success: false,
                message: '状态不能为空'
            });
        }
        
        // 验证状态值是否合法
        const validStatuses = ['pending', 'paid', 'shipping', 'completed', 'cancelled', 'refunded'];
        if (!validStatuses.includes(status)) {
            return res.status(400).json({
                success: false,
                message: '无效的状态值'
            });
        }
        
        await Product.updateProductOrderStatus(orderId, status);
        
        res.json({
            success: true,
            message: '订单状态更新成功'
        });
    } catch (error) {
        console.error('[CONTROLLER] 更新产品订单状态失败:', error);
        res.status(500).json({
            success: false,
            message: '更新产品订单状态失败'
        });
    }
};

module.exports = {
    getProducts,
    getProductDetail,
    createProductOrder,
    getUserProductOrders,
    getStoreProductOrders,
    updateProductOrderStatus
}; 